<?php

class MediaCategory extends CActiveRecord {
    /**
     * The followings are the available columns in table 'www_media_categories':
     * @var integer $id
     * @var string $name
     * @var integer $parent_id
     * @var integer $order_pos
     * @var integer $files_count
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{media_categories}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('name, parent_id', 'required'),
            array('parent_id, order_pos, files_count, created, updated', 'numerical', 'integerOnly'=>true),
            array('name', 'length', 'max'=>200),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
            'media' => array(self::HAS_MANY, 'Media', 'id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'name' => Yii::t('mediaCategory', 'name'),
            'parent_id' => Yii::t('mediaCategory', 'parent_id'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'files_count' => Yii::t('mediaCategory', 'files_count'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    public $files_count = 0;

    public function getUpdateFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    // 排序选项
    public function getOrderPosOptions() {
        $order = array();
        for ($i = 1; $i<= 20; $i++) {
            $order[$i] = "⇑　" . sprintf("%02d", $i) . '　↵';
        }
        return $order;
    }

    private $_ids;
    public function getIds($parent_id = 1, $include_self = true, $include_subs = true) {
        if ($include_self) $this->_ids[] = $parent_id;
        $criteria = new CDbCriteria();
        $criteria->condition = "parent_id = {$parent_id}";
        $criteria->select = array('id');
        $nodes = MediaCategory::model()->findAll($criteria);
        foreach ($nodes as $node) {
            $node_id = $node->id;
            if ($include_subs) {
                if ($this->hasChild($node_id)) {
                    $this->_ids[] = $node_id;
                    $this->getIds($node_id);
                } else {
                    $this->_ids[] = $node_id;
                }
            } else {
                $this->_ids[] = $node_id;
            }
        }
        
        return (count($this->_ids)) ? array_unique($this->_ids) : $this->_ids;
    }

    /**
     * 返回 CTreeView 所需数据
     * @param <integer> $parent_id
     * @param string $url
     * @return <string>
     */
    public function getCTreeViewDatas($parent_id = 1, $url = 'mediaCategories/list') {
        $datas = $this->generateCTreeViewDatas($parent_id, $url);
        return (count($datas) && $datas != null)
            ? CArrayExt::toTree($datas, 'id', 'parent', 'children', $refs)
            : $datas;
    }

    // 遍历节点属于 $parent_id 的所有子节点，供 getCTreeViewDatas 生成返回 CTreeView 所需数据
    private $_CTreeView_datas;
    public function generateCTreeViewDatas($parent_id = 1, $url = 'mediaCategories/list') {
        $criteria = new CDbCriteria;
        $criteria->condition = "parent_id = {$parent_id}";
        $criteria->order = 'order_pos ASC';
        $nodes = MediaCategory::model()->findAll($criteria);
        foreach ($nodes as $j => $node) {
            $node_id = $node->id;
            if ($this->hasChild($node_id)) {
                $this->_CTreeView_datas[$node_id] = array(
                    'id' => $node_id,
                    'text' => CHtml::link($node->name, array($url, 'id' => $node->id)),
//                    'text' => "<span>{$node->name}</span>",
                    'expanded' => true,
                    'classes' => 'important',
                    'parent' => $node->parent_id,
                    'order_pos' => $node->order_pos,
                    'files_count' => $node->files_count,
                );
                $this->generateCTreeViewDatas($node_id, $url);
            } else {
                $this->_CTreeView_datas[$node_id] = array(
                    'id' => $node_id,
                    'text' => CHtml::link($node->name, array($url, 'id' => $node->id)),
                    'expanded' => false,
                    'classes' => 'important',
                    'parent' => $node->parent_id,
                    'order_pos' => $node->order_pos,
                    'files_count' => $node->files_count,
                );
            }
        }

        return $this->_CTreeView_datas;
    }

    /**
     * 判断是否有子节点
     * @param integer $node_id
     * @return boolean
     */
    private static function hasChild($node_id) {
        $criteria = new CDbCriteria;
        $criteria->condition = "parent_id = {$node_id}";
        return (MediaCategory::model()->count($criteria)) ? true : false;
    }

    // 格式化更新时间
    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '-';
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    // 删除 MediaCategory 同时删除 MedaiCategory 下的所有文件。
    protected function afterDelete() {
        $media = Media::model()->findAll("category_id = {$this->id}");
        foreach ($media as $file) {
            Media::model()->findByPk($file->id)->delete();
        }
    }
}